// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
// HTTP server example. This server serves both static and dynamic content.
// It opens two ports: plain HTTP on port 8000 and HTTP on port 8443.
// It implements the following endpoints:
//    /api/stats - respond with free-formatted stats on current connections
//    /api/f2/:id - wildcard example, respond with JSON string {"result": "URI"}
//    any other URI serves static files from s_root_dir
//
// To enable SSL/TLS (using self-signed certificates in PEM files),
//    1. See https://mongoose.ws/tutorials/tls/#how-to-build
//    2. curl -k https://127.0.0.1:8443

#include "mongoose.h"
#include "queue.h"
#include <sys/socket.h>

static const char *s_http_addr = "http://0.0.0.0:8000"; // HTTP port

char recvbuf[1024 * 8];
static void fn(struct mg_connection *c, int ev, void *ev_data)
{
	if (ev == MG_EV_HTTP_MSG) {
		struct mg_http_message *hm = (struct mg_http_message *)ev_data;
		struct mg_str json = hm->body;
		char *str = mg_json_get_str(json, "$.Active");
		send_msg(CTRL_QUEUE, json.buf, json.len);
		if (strncmp(str, "BASE_INFO", strlen(str)) == 0 ||

		    strncmp(str, "SET_NETWORK_CFG", strlen(str)) == 0 ||

		    strncmp(str, "GET_NETWORK_CFG", strlen(str)) == 0) {
			send_msg(SERVICE_QUEUE_REQ, json.buf, json.len);
		} else {
			send_msg(CTRL_QUEUE, json.buf, json.len);
		}
		if (strstr(str, "SET")) {
			snprintf(recvbuf, sizeof(recvbuf), "%s", "{\"Code\" : \"200\", \"Message\" : \"sucess\"}");
			mg_http_reply(c, 200, "Content-type:application/json\r\n", "%.*s\n", strlen(recvbuf), recvbuf);
		} else {
			timerecv_msg(SERVICE_QUEUE_RSP, recvbuf, sizeof(recvbuf));
			mg_http_reply(c, 200, "Content-type:application/json\r\n", "%.*s\n", strlen(recvbuf), recvbuf);
		}
	}
}

int main(void)
{
	struct mg_mgr mgr; // Event manager
	mg_log_set(MG_LL_DEBUG); // Set log level
	mg_mgr_init(&mgr); // Initialise event manager
	mg_http_listen(&mgr, s_http_addr, fn, NULL); // Create HTTP listener
	for (;;)
		mg_mgr_poll(&mgr, 1000); // Infinite event loop
	mg_mgr_free(&mgr);
	return 0;
}
